#!/usr/bin/env node

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import * as fs from "fs";
import * as path from "path";

const server = new McpServer({
  name: "time-server",
  version: "1.0.0",
});

// 获取当前时间工具
server.tool(
  "get_current_time",
  {
    format: z.enum(["timestamp", "iso", "local", "custom"]).optional(),
    customFormat: z.string().optional(),
    timezone: z.string().optional(),
  },
  async ({ format = "iso", customFormat, timezone }) => {
    const now = new Date();

    let result: any = {
      timestamp: now.getTime(),
      iso: now.toISOString(),
      local: now.toLocaleString(),
    };

    if (timezone && typeof timezone === "string") {
      result.timezone = now.toLocaleString("en-US", { timeZone: timezone });
    }

    if (
      format === "custom" &&
      customFormat &&
      typeof customFormat === "string"
    ) {
      result.formatted = formatCustomTime(now, customFormat);
    }

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  }
);

// 格式化时间工具
server.tool(
  "format_time",
  {
    timestamp: z.number(),
    format: z.enum(["iso", "local", "custom"]).optional(),
    customFormat: z.string().optional(),
    timezone: z.string().optional(),
  },
  async ({ timestamp, format = "iso", customFormat, timezone }) => {
    const date = new Date(timestamp);
    let result: any = {};

    switch (format) {
      case "iso":
        result.formatted = date.toISOString();
        break;
      case "local":
        result.formatted = date.toLocaleString();
        break;
      case "custom":
        if (customFormat && typeof customFormat === "string") {
          result.formatted = formatCustomTime(date, customFormat);
        } else {
          result.formatted = date.toISOString();
        }
        break;
    }

    if (timezone && typeof timezone === "string") {
      result.timezone = date.toLocaleString("en-US", { timeZone: timezone });
    }

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  }
);

// 更新文件时间戳工具
server.tool(
  "update_file_timestamp",
  {
    filePath: z.string(),
    pattern: z.string().optional(),
    replacement: z.string().optional(),
  },
  async ({ filePath, pattern, replacement }) => {
    try {
      const absolutePath = path.resolve(filePath);
      const content = fs.readFileSync(absolutePath, "utf8");
      const now = new Date();

      const regexPattern =
        pattern || "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
      const replacementText =
        replacement ||
        now
          .toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
          })
          .replace(/\//g, "-");

      const updatedContent = content.replace(
        new RegExp(regexPattern, "g"),
        replacementText
      );
      fs.writeFileSync(absolutePath, updatedContent, "utf8");

      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              {
                success: true,
                filePath: absolutePath,
                timestamp: replacementText,
                message: "文件时间戳已更新",
              },
              null,
              2
            ),
          },
        ],
      };
    } catch (error) {
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              {
                success: false,
                error: `文件操作失败: ${error}`,
              },
              null,
              2
            ),
          },
        ],
        isError: true,
      };
    }
  }
);

// 计算时间差工具
server.tool(
  "calculate_time_difference",
  {
    startTime: z.string(),
    endTime: z.string().optional(),
    unit: z
      .enum(["milliseconds", "seconds", "minutes", "hours", "days"])
      .optional(),
  },
  async ({ startTime, endTime, unit = "milliseconds" }) => {
    const start = new Date(startTime);
    const end = endTime ? new Date(endTime) : new Date();

    const diffMs = end.getTime() - start.getTime();
    let result: any = {
      startTime: start.toISOString(),
      endTime: end.toISOString(),
      difference: {},
    };

    switch (unit) {
      case "milliseconds":
        result.difference.milliseconds = diffMs;
        break;
      case "seconds":
        result.difference.seconds = diffMs / 1000;
        break;
      case "minutes":
        result.difference.minutes = diffMs / (1000 * 60);
        break;
      case "hours":
        result.difference.hours = diffMs / (1000 * 60 * 60);
        break;
      case "days":
        result.difference.days = diffMs / (1000 * 60 * 60 * 24);
        break;
    }

    // 同时提供所有单位的换算
    result.allUnits = {
      milliseconds: diffMs,
      seconds: diffMs / 1000,
      minutes: diffMs / (1000 * 60),
      hours: diffMs / (1000 * 60 * 60),
      days: diffMs / (1000 * 60 * 60 * 24),
    };

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result, null, 2),
        },
      ],
    };
  }
);

// 简单的自定义时间格式化函数
function formatCustomTime(date: Date, format: string): string {
  const replacements: { [key: string]: string } = {
    YYYY: date.getFullYear().toString(),
    MM: (date.getMonth() + 1).toString().padStart(2, "0"),
    DD: date.getDate().toString().padStart(2, "0"),
    HH: date.getHours().toString().padStart(2, "0"),
    mm: date.getMinutes().toString().padStart(2, "0"),
    ss: date.getSeconds().toString().padStart(2, "0"),
  };

  let result = format;
  for (const [pattern, replacement] of Object.entries(replacements)) {
    result = result.replace(new RegExp(pattern, "g"), replacement);
  }
  return result;
}

async function runServer() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MCP Time Server running on stdio");
}

runServer().catch((error) => {
  console.error("Fatal error in main():", error);
  process.exit(1);
});
